<script setup>
import reserveApi from "@/api/reserve.js";
import {ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import { Plus } from '@element-plus/icons-vue'
import router from "@/router/index.js";
import WangEditor from "@/components/WangEditor.vue";
//数据表格
const list = ref([])
const total = ref(0)
//分页信息和搜索条件
const reserveQuery = ref({
  name: '',
  phone: '',
  courseId:'',
  userId:'',
  page: 1,
  limit: 10
})

/*reserveApi.list(reserveQuery.value).then(result => {
    list.value = result.data.records
    total.value = result.data.total
})*/

const loadData = () => {
  reserveApi.list(reserveQuery.value).then(result => {
    if (result.code == 0) {
      list.value = result.data.records
      total.value = result.data.total
    }
  })
}

loadData()

const onSearch = () => {
  reserveQuery.value.page = 1
  loadData()
}

const reset = () => {
  reserveQuery.value.courseId = ''
  reserveQuery.value.userId = ''
  reserveQuery.value.beginUpdateTime = null
  reserveQuery.value.endUpdateTime = null


}

//根据id删除
const deleteById = (id) => {
  ElMessageBox.confirm(
      '您确认要删除么?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    reserveApi.deleteById(id).then(result => {
      if (result.code == 0) {
        ElMessage.success(result.msg)
        loadData()
      } else {
        ElMessage.error(result.msg)
      }
    })
  })
}

//批量删除
const ids = ref([])
const handleSelectionChange = (rows) => {
  console.log('多选', rows)
  ids.value = rows.map(function (row) {
    return row.id;
  })
  console.log(ids.value)
}

const deleteAll = () => {
  ElMessageBox.confirm(
      '您确认要删除么?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    reserveApi.deleteAll(ids.value).then(result => {
      if (result.code == 0) {
        ElMessage.success(result.msg)
        loadData()
      } else {
        ElMessage.error(result.msg)
      }
    })
  })
}

//添加、编辑
const dialogFormVisible = ref(false)
const reserve = ref({})
const showAddDialog = () => {
  reserve.value = {}
  dialogFormVisible.value = true
}

const showUpdateDialog = (id) => {
  dialogFormVisible.value = true
  reserve.value = {}
  reserveApi.selectById(id).then(result => {
    if (result.code == 0) {
      reserve.value = result.data
    }
  })
}

const addOrUpdate = async () => {
  if (reserve.value.id) {
    // 编辑直接走原来的更新逻辑
    reserveApi.update(reserve.value).then(result => {
      if (result.code == 0) {
        ElMessage.success(result.msg)
        dialogFormVisible.value = false
        loadData()
      } else {
        ElMessage.error(result.msg)
      }
    })
  } else {
    // 添加预约前先检查重复
    try {
      const allReserves = await reserveApi.selectAll()
      if (allReserves.code === 0) {
        const exists = allReserves.data.some(
            item =>
                item.userId === reserve.value.userId &&
                item.courseId === reserve.value.courseId
        )
        if (exists) {
          ElMessage.warning('该用户已预约该课程')
          return
        }
      }
      // 不存在重复才添加
      const result = await reserveApi.add(reserve.value)
      if (result.code === 0) {
        ElMessage.success(result.msg)
        dialogFormVisible.value = false
        loadData()
      } else {
        ElMessage.error(result.msg)
      }
    } catch (err) {
      console.error(err)
      ElMessage.error('检查预约重复失败')
    }
  }
}



//el-switch状态切换
const handleSwitchChange = (row) => {
  console.log(row)
  const reserve = {}
  reserve.id = row.id
  reserve.status = row.status
  reserveApi.update(reserve).then(result => {
    if (result.code == 0) {
      ElMessage.success(result.msg)
    } else {
      ElMessage.error(result.msg)
    }
  })
  /*reserveApi.updateStatus(row.id, row.status).then(result => {
      if (result.code == 0) {
          ElMessage.success(result.msg)
      } else {
          ElMessage.error(result.msg)
      }
  })*/
}

//图片上传
const handleAvatarSuccess = (result) => {
  reserve.value.avatar = result.data
}

import {useTokenStore} from '@/store/token.js'
import courseApi from "@/api/course.js";
import userApi from "@/api/user.js";
const tokenStore = useTokenStore();
const headers = ref({
  //携带token传递到后端
  Authorization: tokenStore.token
});

//查找所有的课程
const courseList = ref([])
courseApi.selectAll().then(result => {
  if (result.code == 0) {
    courseList.value = result.data
  }
})

//查找所有的user
const userList = ref([])
userApi.selectAll().then(result => {
  if (result.code == 0) {
    userList.value = result.data
  }
})


//下拉事件
const selectChange = (value) => {
  console.log(value)
}


//富文本编辑器
const onEditorChange = (introduction) => {
  reserve.value.introduction = introduction
}

const dialogIntroductionVisible = ref(false)
const introduction = ref('')
const showIntroduction = (intro) => {
  dialogIntroductionVisible.value = true
  introduction.value = intro
}
</script>

<template>
  <el-card class="">
    <template #header>
      <div class="header">
        <el-button type="success" @click="showAddDialog">添加预约</el-button>
        <el-button type="danger" @click="deleteAll">批量删除</el-button>
      </div>
    </template>
    <el-form :inline="true">
      <el-form-item label="课程">
        <el-select @change="selectChange" v-model="reserveQuery.courseId" clearable placeholder="请选择课程"
                   style="width: 150px">
          <el-option
              v-for="course in courseList"
              :key="course.id"
              :label="course.name"
              :value="course.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户">
        <el-select @change="selectChange" v-model="reserveQuery.userId" clearable placeholder="请选择用户"
                   style="width: 150px">
          <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.name"
              :value="user.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="更新时间" :label-width="100">
        <el-date-picker
            v-model="reserveQuery.beginUpdateTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="开始时间"
        />
        <el-date-picker
            v-model="reserveQuery.endUpdateTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="结束时间"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button type="warning" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="list" style="width: 100%" ref="multipleTableRef" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column fixed prop="id" label="ID"/>
      <el-table-column prop="courseId" label="课程ID"/>
      <el-table-column prop="courseName" label="课程"/>
      <el-table-column prop="userId" label="用户ID"/>
      <el-table-column prop="userName" label="用户"/>
      <el-table-column prop="score" label="评分"/>
      <el-table-column prop="comment" label="评价"/>
<!--      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-switch
              v-model="scope.row.status"
              style="&#45;&#45;el-switch-on-color: #13ce66; &#45;&#45;el-switch-off-color: #ff4949"
              :active-value="1"
              :inactive-value="0"
              @change="handleSwitchChange(scope.row)"
          />
        </template>
      </el-table-column>-->
      <!-- <el-table-column prop="avatar" label="头像"/> -->
      <el-table-column prop="updateTime" label="更新时间" width="180px"/>
      <el-table-column align="center" width="200px" fixed="right" label="操作">
        <template #default="{ row }">
<!--
          <el-button size="small" type="primary" @click="showUpdateDialog(row.id)">编辑</el-button>
-->
          <el-button size="small" type="danger" @click="deleteById(row.id)">删除</el-button>
<!--
          <el-button size="small" type="warning" @click="showIntroduction(row.introduction)">备注</el-button>
-->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="reserveQuery.page"
        v-model:page-size="reserveQuery.limit"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @change="loadData"
        style="margin-top: 20px; justify-content: flex-end"
    />
  </el-card>

  <!--添加、编辑弹出框-->
  <el-dialog v-model="dialogFormVisible" :title="title" width="60%" :lock-scroll="false">
    <el-form :model="reserve">
      <el-form-item label="课程">
        <el-select @change="selectChange" v-model="reserve.courseId" clearable placeholder="请选择课程"
                   style="width: 150px">
          <el-option
              v-for="course in courseList"
              :key="course.id"
              :label="course.name"
              :value="course.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户">
        <el-select @change="selectChange" v-model="reserve.userId" clearable placeholder="请选择用户"
                   style="width: 150px">
          <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.name"
              :value="user.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="评分" :label-width="60">
        <!-- 只读文本展示 -->
        <span>{{ reserve.score }}</span>
        <!-- 或者如果你想保留输入框样式 -->
         <el-input v-model="reserve.score" disabled />
      </el-form-item>

      <el-form-item label="评价" :label-width="60">
        <!-- 只读文本展示 -->
        <span>{{ reserve.comment }}</span>
        <!-- 或者保留输入框 -->
         <el-input v-model="reserve.comment" disabled />
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="addOrUpdate">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="dialogIntroductionVisible" :title="title" width="60%" :lock-scroll="false">
    <div v-html="introduction"></div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="dialogIntroductionVisible = false">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>